from OWRpy import *
import redRi18n
_ = redRi18n.get_(package = 'base')

import signals 
import redRGUI 

class compPred(OWRpy): 
    globalSettingsList = ['commit']
    def __init__(self, **kwargs):
        OWRpy.__init__(self, **kwargs)
        self.setRvariableNames(["lm"])
        self.RFunctionParam_formula = ""
        self.RFunctionParam_data = {}
        self.RFunctionParam_Rclass = {}
        self.RFunctionParam_Cnames = {}
        self.RFunctionParam_elementsList = []
        self.modelFormula = ''
        self.processingComplete = 0
        
        self.saveSettingsList = ['RFunctionParam_data']
        
        # Inputs
        self.inputs.addInput('id0', 'variables', signals.base.RMatrix, self.processdata, multiple = True)
        self.inputs.addInput('id1', 'predictors', signals.base.RVector, self.processdata, multiple = True)
        
        # Outputs
        self.outputs.addOutput('id0', 'Predicted values', signals.base.RMatrix)
        self.outputs.addOutput('id1', 'Predicted plot attribute line', signals.plotting.RPlotAttribute)

        # Unique R variables
        self.setRvariableNames(["compPred"])

        #GUI
        
        box = redRGUI.base.widgetBox(self.controlArea, orientation = 'horizontal')
        #paramBox = redRGUI.base.groupBox(self.GUIDialog, 'Parameters')
        formulaBox = redRGUI.base.widgetBox(self.controlArea)

        #start formula entry section

        buttonsBox = redRGUI.base.widgetBox(formulaBox, "Commands")
        self.formulEntry = redRGUI.base.RFormulaEntry(buttonsBox,label='Formula',displayLabel=False)
        self.formulEntry.colonButton.hide()
        self.formulEntry.outcomeVariable.hide()
        
        
        self.commit = redRGUI.base.commitButton(self.bottomAreaRight, "Commit", callback = self.commitFunction,
        processOnInput=True)
        #self.processButton.setEnabled(False)
        self.status.setText('Data Not Connected Yet')

    def processdata(self, data, id):
        if data:
            self.RFunctionParam_data[id] = data.getData()
            self.RFunctionParam_Cnames[id]=[]
            if self.R('is.vector('+self.RFunctionParam_data[id]+')') == True :
                self.RFunctionParam_Cnames[id].append(self.RFunctionParam_data[id])
            else:
                self.columnNames = self.R('colnames('+self.RFunctionParam_data[id]+')')
                print '!column names: ', self.columnNames
                for i in range(0, self.R('ncol('+self.RFunctionParam_data[id]+')') ):
                    print '!i: ', i
                    #self.tempPaste=self.R( 'paste("acomp(", "'+self.RFunctionParam_data[id]+'","$","'+self.columnNames[i]+'",")", sep="")' )
                    self.tempPaste=self.R( 'paste("acomp(as.data.frame('+self.RFunctionParam_data[id]+')$'+self.columnNames[i]+')", sep="")' )
                    self.RFunctionParam_Cnames[id].append(self.tempPaste)

            for i in range(len(self.RFunctionParam_Cnames[id])):
                self.RFunctionParam_elementsList.append(self.RFunctionParam_Cnames[id][i])

            self.formulEntry.update(self.RFunctionParam_elementsList)
            self.status.setText('Data Connected')
            if self.commit.processOnInput():
                self.commitFunction()
        else:
            self.formulEntry.clear()
            self.RFunctionParam_data = ''
            del self.RFunctionParam_data[id]
            self.status.setText('Data Connection Failed. Please Reconnect')

    def commitFunction(self):
        if self.RFunctionParam_data == '': 
            self.status.setText('No data')
            return
        if self.formulEntry.Formula() == '':
            self.status.setText('Please select valid formula parameters')
            return
        
        print '!Formule unicode: ', unicode(self.formulEntry.Formula())[0]
        print '!Formule 0: ', self.formulEntry.Formula()[0]
        print '!Formule 1: ', self.formulEntry.Formula()[1]
        
        self.R(self.Rvariables['compPred']+'<-'+unicode(self.formulEntry.Formula()[1]), wantType = 'NoConversion')
        
        
        
        newData = signals.base.RMatrix(self, data = self.Rvariables['compPred'], checkVal=False)
        self.rSend("id0", newData)
        
        newPlotAtt = signals.plotting.RPlotAttribute(self, data = 'lines(%s, pch = %s, lty = %s)' % (self.Rvariables['compPred'], 20, 2))
        #lines(compPred, col="red")
        #newPlotAtt = redRRPlotAttribute(self, data = 'abline('+self.Rvariables['lm']+')')
        
        self.rSend("id1", newPlotAtt)
        
